package com.jijs.jmx.modeler.demo;

import java.io.InputStream;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBean;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.modeler.ManagedBean;
import org.apache.commons.modeler.Registry;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class MyMBeanServer {

	public static void main(String[] args) throws Exception {
		Registry registry = Registry.getRegistry();
		InputStream stream = MyMBeanServer.class.getResourceAsStream("Mbeans-descriptors.xml");
		registry.loadRegistry(stream);
		stream.close();
		MBeanServer mserver = registry.getMBeanServer();

		/* 创建被管理的资源实例 */
		TestBean bean = new TestBean();
		/*
		 * Modeler 组件提供的对 managedbean 配置信息的封装对象， 通过它 建立资源和 ModelMBean 的联系
		 */
		ManagedBean managed = registry.findManagedBean("TestBean");
		String domain = managed.getDomain();
		/* 得到 ModelMbean */
		ModelMBean mbean = managed.createMBean(bean);
		/* 创建 ObjectName */
		ObjectName oname = new ObjectName(domain + ":test=jjs");
		/* 注册 MBean */
		mserver.registerMBean(mbean, oname);

		// MBeanServerConnector 的实现。
		// 在 JMXRemoteAPI 发布之后， Agent 需要提供 ConnectorServer，我们可
		// 以这样注册一个 JMXMP 的 ConnectorServer.
		/* 定义 JMXServiceURL 这个对象是客户端和服务器联系的关键 */
		JMXServiceURL address = new JMXServiceURL("jmxmp", null, 7777);
		JMXConnectorServer connectorSrv = JMXConnectorServerFactory.newJMXConnectorServer(address, null, null);
		ObjectName csName = new ObjectName(":type=cserver,name=mycserver");
		mserver.registerMBean(connectorSrv, csName);
		connectorSrv.start();
		
		HtmlAdaptorServer madaptor = new HtmlAdaptorServer();
		mserver.registerMBean(madaptor,new ObjectName("adaptor:protocol=HTTP"));
		madaptor.setPort(8888);
		madaptor.start();
		System.out.println("start.....");
	}
}
